<?php

/**
 * 余额支付类
 * @author chenlisong E-mail:chenlisong1021@163.com
 * @version 创建时间：2016年11月14日 上午10:42:32
 * 类说明
 */
class PayAction extends BaseAction
{


    /**
     * 余额支付
     */
    public function balancePayOrder()
    {
        $Order = M('Order');
        $User = M('User');
        $UserDetails = M("UserDetails");
        $Shop = M("Shop");
        $OrderDetails = M('OrderDetails');
        $Product = M('Product');
        $ShopProduct = M("ShopProduct");
        $ShopAttributeValues = M("ShopAttributeValues");
        $param = $this->param;
        $Order->startTrans();
        if (empty($param['orderCode'])) {
            echo $this->err("参数错误！");
            return;
        }
        //判断订单状态是否正确
        $where['code'] = $param['orderCode'];
        $where['flag'] = 1;
        $where['status'] = 1;
        $info = $Order->where($where)->find();
        if (count($info) == 0) {
            echo $this->err("错误的订单状态，请重新下单！");
            return;
        }
        //判断余额是否充足
        $balance = (float)$User->where('flag = 1 and id = ' . $param['userId'])->getField('balance');

        //扣除库存
        $orderDetails = $OrderDetails->where(array('order_code' => $info['code'], 'flag' => 1))->select();
        $querySql = 'SET num = CASE id ';
        $queryIds = "";

        $querySql_s = 'SET num = CASE product_id ';
        $queryIds_s = "";

        $querySql_1 = 'SET num = CASE id ';
        $queryIds_1 = "";
        $vip_discount = 0;
        foreach ($orderDetails as $pk => $pv) {
            $productInfo = $Product->where(array('id' => $pv['product_id'], 'flag' => 1))->find();
            $shopProductInfo = $ShopProduct->field("num")->where(array('product_id' => $pv['product_id'], 'flag' => 1,'shop_id'=>$info['shop_id']))->find();
            $sellNum = $pv['num'];

            if ($pv['attribute_values'] != "") {
                $attr_value_arr = explode(':', $pv['attribute_values']);
                $attr_value_name = $attr_value_arr[1];
                $attribute_values = $ShopAttributeValues->where(array("product_id" => $pv['product_id'], 'attr_value_name' => $attr_value_name))->find();
                if ($attribute_values) {
                    if ($sellNum > $attribute_values['num']) {
                        echo $this->err($pv['name'] . '库存不足，请重新选择商品！');
                        return;
                    }
                }
            } else {
                if ($sellNum > $shopProductInfo['num']) {
                    echo $this->err($pv['name'] . '库存不足，请重新选择商品！');
                    return;
                }
            }
            //商品下架
            if ($productInfo['is_on'] == 2) {
                echo $this->err($pv['name'] . '已下架，请重新选择商品！');
                return;
            }

            //计算优惠金额
            if ($productInfo['vip_price'] > 0) {
                $vip_discount = $vip_discount + ($productInfo['price'] - $productInfo['vip_price']) * $sellNum;

            }
            //组装扣除商品数量sql
            if ($pv['attribute_values'] != "") {
                $querySql_1 .= ' WHEN ' . $pv['attr_values_id'] . ' THEN num -' . $sellNum . " ";
                $queryIds_1 .= $pv['attr_values_id'] . ",";
            } else {
                $querySql .= ' WHEN ' . $pv['product_id'] . ' THEN num -' . $sellNum . " ";
                $queryIds .= $pv['product_id'] . ",";

                $querySql_s .= ' WHEN ' . $pv['product_id'] . ' THEN num -' . $sellNum . " ";
                $queryIds_s .= $pv['product_id'] . ",";
            }

        }
        if ($queryIds_1 != '') {
            $querySql_1 .= ' END ';
            $queryIds_1 = substr($queryIds_1, 0, strlen($queryIds_1) - 1);
            $querySql_1 .= 'where id in (' . $queryIds_1 . ') and shop_id='.$info['shop_id'];
        }
        if ($queryIds != '') {
            $querySql .= ' END ';
            $queryIds = substr($queryIds, 0, strlen($queryIds) - 1);
            $querySql .= 'where id in (' . $queryIds . ')';
        }

        if ($queryIds_s != '') {
            $querySql_s .= ' END ';
            $queryIds_s = substr($queryIds_s, 0, strlen($queryIds_s) - 1);
            $querySql_s .= 'where product_id in (' . $queryIds_s . ') and shop_id=' . $info['shop_id'];
        }
        //实际金额等于总金额-优惠金额
        if ($vip_discount > 0) {
            $data['real_price'] = $info['total_price'] - $vip_discount;
            $price = $info['real_price'] + $info['mail_fee'] - $vip_discount;
        } else {
            $price = $info['real_price'] + $info['mail_fee'];
        }

        if ($price > $balance) {
            echo $this->err("余额不足，请先充值！");
            return;
        }

        //记录明细
        $detailData['user_id'] = $param['userId'];
        $detailData['title'] = "订单支付";
        $detailData['type'] = 2;
        $detailData['price'] = $price;
        $detailData['last_price'] = $balance;
        $detailData['create_time'] = time();
        $result1 = $UserDetails->add($detailData);
        $result2 = $User->where('flag = 1 and id = ' . $param['userId'])->setDec('balance', $price);

        //订单状态更改
        $data['status'] = 2;
        $data['flag'] = 1;
        $data['pay_type'] = 3;
        $data['pay_time'] = time();
        $data['update_time'] = time();
        $result3 = $Order->where($where)->save($data);

        //扣除商品表库存
        if ($queryIds != '') {
            $Product->execute('update __TABLE__ ' . $querySql);
        }
        //扣除规格库存
        if ($queryIds_1 != '') {
            $ShopAttributeValues->execute('update __TABLE__ ' . $querySql_1);
        }
        //扣除店铺商品库存
        if ($queryIds_s != '') {
            $ShopProduct->execute('update __TABLE__ ' . $querySql_s);
            writeLog("【sql】：" .$querySql_s);
        }


        if ($result1 && $result2 && $result3 !== false) {
            $Order->commit();
            $Shopinfo = $Shop->where(array("id" => $info['shop_id']))->field("user_id")->find();
            $this->insertNotice($Shopinfo['user_id'], "您有未处理的订单！", $info['code']);
            echo $this->suc();
        } else {
            $Order->rollback();
            echo $this->err("支付失败！");
        }
    }

    /**
     * 新增消息
     * 新增商家待处理订单消息
     */
    private function insertNotice($userId, $message, $ambulance)
    {
        $Notice = M('Notice');
        $User = M('User');
        $jpushId = $User->where('id = ' . $userId)->getField('jpush_id');
        if (!empty($jpushId)) {
            $data['type'] = 4;
            $data['user_id'] = $userId;
            $data['message'] = $message;
            $data['ambulance'] = $ambulance;
            $data['create_time'] = time();
            $Notice->add($data);
        }
        return true;
    }
}